package com.tfswue.lh.controller;

import com.tfswue.lh.service.EventPublisherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class RegestController {
    
    private static final Logger logger = LoggerFactory.getLogger(RegestController.class);
    
    @Autowired
    private EventPublisherService eventPublisher;

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> registerUser(
            @RequestParam String username,
            @RequestParam String email) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 输入验证
            if (!StringUtils.hasText(username)) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (!StringUtils.hasText(email) || !email.contains("@")) {
                response.put("success", false);
                response.put("message", "邮箱格式不正确");
                return ResponseEntity.badRequest().body(response);
            }
            
            logger.info("开始处理用户注册: username={}, email={}", username, email);
            
            // 这里可以添加实际的用户注册业务逻辑
            // 例如：保存到数据库、验证用户名是否已存在等
            
            // 发布用户注册事件
            eventPublisher.publishUserRegistered(username, email);
            
            response.put("success", true);
            response.put("message", "注册成功");
            response.put("data", Map.of("username", username, "email", email));
            
            logger.info("用户注册成功: username={}", username);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("用户注册失败: username={}, email={}", username, email, e);
            response.put("success", false);
            response.put("message", "注册失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
}